package summer.dp;

public class Solution718 {
    public int findLength1(int[] nums1, int[] nums2) {
        int l1 = nums1.length;
        int l2 = nums2.length;
        int[][] dp = new int[l1][l2];
        int res = Integer.MIN_VALUE;
        for (int i = 0; i < l2; i++) {
            if (nums2[i] == nums1[0]) {
                dp[0][i] = 1;
                res = 1;
            }
        }
        for (int i = 0; i < l1; i++) {
            if (nums1[i] == nums2[0]) {
                dp[i][0] = 1;
                res = 1;
            }
        }

        for (int i = 1; i < l1; i++) {
            for (int j = 1; j < l2; j++) {
                if (nums1[i] == nums2[j]) dp[i][j] = dp[i - 1][j - 1] + 1;
                else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                res = Math.max(res, dp[i][j]);
            }
        }
        return res;
    }

    public int findLength(int[] nums1, int[] nums2) {
        int l1 = nums1.length;
        int l2 = nums2.length;
        int[][] dp = new int[l1 + 1][l2 + 1];
        int res = Integer.MIN_VALUE;
        for (int i = 0; i < l1; i++) {
            for (int j = 0; j < l2; j++) {
                if (nums1[i] == nums2[j]) dp[i + 1][j + 1] = dp[i][j] + 1;
                res = Math.max(res, dp[i + 1][j + 1]);
            }
        }
        return res;
    }
}
